<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { ref, reactive } from 'vue'
import { getMyFilePage } from '@/api/my-file/index'
import type { MyFileQuery, MyFileVO } from '@/api/my-file/types';
import { useMemberStore } from '@/stores'
import { baseURL } from '@/utils/http'
import type { LoginResult } from '@/types/member';

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

type MySwipeActionItem = MyFileVO & { show: boolean }

// 查询总条数
const total = ref(0);
// 查询参数
const queryParams = reactive<MyFileQuery>({
  pageNum: 1,
  pageSize: 10,
  searchType: "search",
});

// 列表
const fileTableList = ref<MySwipeActionItem[]>([])
// 查询方法
const getListData = () => {
  const memberStore = useMemberStore()
  queryParams.empId = memberStore.userInfo?.userId
  getMyFilePage(queryParams).then(res => {
    if (res.msg !== '执行成功') {
      uni.showToast({ icon: 'error', title: '登录失败' })
      return
    }
    fileTableList.value = res.data.list.map(item => {
      return { show: false, ...item }
    })
    total.value = res.data.total;
  })
    .finally(() => { });
}

// 搜索
const keyword = ref('')
const find = async () => {
  // uni.showToast({ icon: "success", title: `find` })
  queryParams.keywords = keyword.value
  getListData()
}


// 是否加载中标记
const isLoading = ref(false)
const empName = ref<string>()
// 页面加载
onLoad(async () => {
  isLoading.value = true
  // await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
  isLoading.value = false
  const memberStore = useMemberStore()
  empName.value = memberStore.userInfo?.nickname
  // 获取数据
  getListData()
})

// 下载
const click = (item: MyFileVO) => {
  const memberStore = useMemberStore()

  // uni.showLoading({
  //   title: '下载中'
  // });

  const filetype = item.fileName.substr(item.fileName.lastIndexOf('.') + 1)//获取文件地址的类型
  console.log('文档', filetype)
  uni.downloadFile({
    url: `${baseURL}/file/my-file/${item.id}/download`,
    header: {
      Authorization: memberStore.profile?.tokenType + " " + memberStore.profile?.accessToken
    },
    success: function (res) {
      if (res.statusCode === 200) {
        // 创建隐藏的可下载链接
        var downloadDom = document.createElement('a');
        downloadDom.style.display = 'none';
        downloadDom.href = res.tempFilePath; // 这是临时文件路径
        downloadDom.setAttribute(
          'download',
          item.fileName // 指定下载时显示的文件名，也可以根据实际情况动态设置
        );

        // 在H5环境下，需要将a标签添加到DOM树中才能触发点击事件
        document.body.appendChild(downloadDom);

        // 触发点击下载
        if (document.createEvent) {
          var event = document.createEvent('MouseEvents');
          event.initEvent('click', true, false);
          downloadDom.dispatchEvent(event);
        } else if (downloadDom.click) {
          downloadDom.click();
        }

        // 下载完成后从DOM移除
        setTimeout(function () {
          document.body.removeChild(downloadDom);
        }, 0);
      } else {
        // 下载失败处理
        uni.showModal({
          title: '提示',
          content: `下载失败,code:${res.statusCode}`,
        });
        console.log(res);
        console.log('下载失败，状态码：' + res.statusCode);
      }
    },
    fail: function (err) {
      console.log(err)
      // 下载失败处理
      uni.showModal({
        title: '提示',
        content: `下载失败`,
      });
      console.error('下载文件失败：', err);
    }
  });
  // uni.downloadFile({
  //   url: `${baseURL}/file/my-file/${item.id}/download`,
  //   header: {
  //     Authorization: memberStore.profile?.tokenType + " " + memberStore.profile?.accessToken
  //   },
  //   success(res) {
  //     if (res.statusCode === 200) {
  //       var myFilePath = `${wx.env.USER_DATA_PATH}/${item.fileName}`
  //       uni.getFileSystemManager().saveFile({
  //         tempFilePath: encodeURI(res.tempFilePath),
  //         filePath: myFilePath,
  //         success(res){
  //           console.log('保存文件成功！',res)
  //           setTimeout(() => {
  //             uni.openDocument({
  //               filePath: res.savedFilePath,
  //               fileType: filetype,//这样文件地址是什么类型，api打开的就是什么类型了，前提是uni.openDocument支持的类型
  //               showMenu: true,
  //               success: function(res) {
  //                 console.log('打开文档成功');
  //                 uni.hideLoading()
  //               },
  //               fail: (e) => {
  //                 // console.log(e, '打开文档失败')
  //                 // uni.showToast({
  //                 //   title: '不支持打开该文件',
  //                 //   icon: "error",
  //                 // })
  //                 uni.hideLoading()
  //                 uni.showModal({
  //                   title: '提示',
  //                   content: `不支持打开该文件，文件已保存在：${res.savedFilePath}`,
  //                 });
  //               }
  //             })
  //           }, 1000);
  //         },
  //         fail(e) {
  //           uni.showToast({
  //             title: '保存文件失败！',
  //             icon: "error",
  //           })
  //           console.log('保存文件失败！')
  //           console.log(e)
  //         }
  //       })
  //     } else {
  //       console.log('下载失败'!);
  //       console.log(res);
  //       uni.showToast({
  //         title: '下载失败',
  //         icon: "error",
  //       })
  //     }
  //   },
  //   fail: (e) => {
  //     console.log(e, '文件下载失败')
  //     uni.showToast({
  //       title: '文件下载失败',
  //       icon: "error",
  //     })
  //   }
  // })
}

// 如果打开一个的时候，不需要关闭其他，则无需实现本方法
const open = (index: number) => {
  // uni.showToast({ icon: "success", title: `open${index}` })
  fileTableList.value[index].show = true;
  fileTableList.value.map((val, idx) => {
    if (index != idx) {
      fileTableList.value[idx].show = false;
    }
  })
}


const options = ref([
  // {
  //   text: '查看',
  //   style: {
  //     backgroundColor: '#3C7DFF'
  //   }
  // },
  {
    text: '下载',
    style: {
      backgroundColor: '#3C7DFF'
    }
  }
])

// 分页
const handlePage = async (e: any) => {
  queryParams.pageNum = e.current
  getListData()
  uni.pageScrollTo({
    scrollTop: 0, // 滚动到页面顶部
    duration: 100 // 可选，滚动动画时长
  });
}

// 注销
const btnLogout = () => {
  const memberStore = useMemberStore()
  memberStore.clearProfile()
  uni.reLaunch({
    url: '/pages/login/login'
  });
}

</script>

<template>
  <view class="viewport">
    <!-- 自定义导航栏 -->
    <view class="navbar" :style="{ paddingTop: safeAreaInsets!.top + 10 + 'px' }">
      <view class="logo">
        <h2 style="color: white;">文件系统 ({{ empName }})</h2>
        <u-button type="success" size="mini" style="margin-left: 5px" @click="btnLogout">注销</u-button>
      </view>
    </view>

    <view style="margin-top: 5px;">
      <u-search shape="round" :show-action="true" action-text="搜索" placeholder="文件名/标题/标签" v-model="keyword"
        @custom="find">
      </u-search>
    </view>

    <view class="details-page">
      <view class="details-page-item">
        <u-swipe-action class="details-item" :show="item.show" :index="index" v-for="(item, index) in fileTableList"
          :key="item.id" @click="click(item)" @open="open(index)" :options="options">
          <view class="details-content-box">
            <text class="details-content-title">
              {{ item.fileName }}
            </text>
            <view class="details-name">
              <view class="details-name-left">
                <!-- <image style="width: 30rpx; height: 30rpx; margin-right: 6rpx;" src="@/static/home/user.svg" mode='aspectFit' class="zai-logo"></image> -->
                <text>{{ item.title }}</text>
              </view>
              <view class="details-name-right">
                <!-- <image style="width: 24rpx; height: 24rpx; margin-right: 6rpx;" src="@/static/home/date.svg" mode='aspectFit' class="zai-logo"></image> -->
                <text>{{ item.tags }}</text>
              </view>
            </view>
            <view class="details-content-page">
              {{ item.notes }}
            </view>
          </view>
        </u-swipe-action>
        <uni-pagination v-if="total > 0" type="bottom" :total="total" :current="queryParams.pageNum"
          :pageSize="queryParams.pageSize" @change="handlePage">
        </uni-pagination>

        <view v-if="fileTableList.length === 0" class="nodata">
          <u-empty text="暂无数据" mode="list"></u-empty>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
/* 自定义导航条 */
.navbar {
  background-image: url(@/static/images/navigator_bg.png);
  background-size: cover;
  position: relative;
  display: flex;
  flex-direction: column;
  padding-top: 20px;

  .logo {
    display: flex;
    align-items: center;
    height: 64rpx;
    padding-left: 30rpx;

    .logo-image {
      width: 166rpx;
      height: 39rpx;
    }

    .logo-text {
      flex: 1;
      line-height: 28rpx;
      color: #fff;
      margin: 2rpx 0 0 20rpx;
      padding-left: 20rpx;
      border-left: 1rpx solid #fff;
      font-size: 26rpx;
    }
  }

  .search {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 10rpx 0 26rpx;
    height: 64rpx;
    margin: 16rpx 20rpx;
    color: #fff;
    font-size: 28rpx;
    border-radius: 32rpx;
    background-color: rgba(255, 255, 255, 0.5);
  }

  .icon-search {
    &::before {
      margin-right: 10rpx;
    }
  }

  .icon-scan {
    font-size: 30rpx;
    padding: 15rpx;
  }
}


.home-box {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
}

.home-page {
  height: 112rpx;
}

.search-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 24rpx;
  box-sizing: border-box;
  background: #3975C6;

  .search-img {
    margin-left: 10rpx;
  }

  .uicon-search {
    color: #CEDDF1;
  }
}

.details-wrap {
  background: #3975C6;
  padding: 30rpx 0;

  ::v-deep .u-steps .u-steps__item__dot {
    position: relative;
    width: 28rpx;
    height: 28rpx;
    // &::after {
    // 	content: '';
    // 	position: absolute;
    // 	left: 50%;
    // 	top: 0;
    // 	margin-left: -4px;
    // 	width: 4px;
    // 	height: 8px;
    // 	border-color: #009933;
    // 	border-style: solid;
    // 	border-width: 0 2px 2px 0;
    // 	transform: rotate(45deg);
    // }
  }
}

.u-iconfont {
  color: #3975C6;
}

.details-page,
.details-page-padding {
  flex: 1 1 auto;

  .details-page-item {
    padding: 24rpx;
  }

  .details-page-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #1F2329;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    line-height: 60rpx;
    position: relative;

    .details-page-line {
      width: 6rpx;
      height: 28rpx;
      background: #377AFF;
      border-radius: 3rpx 3rpx 3rpx 3rpx;
      margin-right: 10rpx;
    }
  }

  .details-item {
    margin-bottom: 10rpx;
  }

  .details-content-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #1F2329;
    padding-left: 48rpx;
    position: relative;
    line-height: 60rpx;
    margin-top: 10rpx;

    &::after {
      width: 38rpx;
      height: 38rpx;
      background: url("@/static/home/title.svg") no-repeat;
      background-size: 100%;
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      margin-top: -19rpx;
    }
  }

  .download {
    position: absolute;
    right: 0;
    font-size: 26rpx;
    color: #8F959E;
  }

  .details-content-box {
    width: 100%;
    padding: 24rpx;
    background: #fff;
    border-radius: 16rpx;
    margin-bottom: 24rpx;

    .details-download-item {
      display: flex;
      padding: 30rpx 0;
      justify-content: flex-start;
      align-items: flex-start;
      border-bottom: 1px solid #D8D8D8;
      font-size: 28rpx;
      font-weight: bold;
      color: #1F2329;
      flex-direction: row;
      position: relative;

      .download-icon {
        position: absolute;
        right: 36rpx;
        top: 25rpx;
      }

      .details-download-p {
        font-size: 24rpx;
        color: #646A73;
        font-weight: normal;

        .time {
          margin-left: 40rpx;
        }
      }
    }
  }

  .details-content-page {
    font-size: 24rpx;
    color: #8F959E;
    padding: 20rpx 0;
  }

  .details-name {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 24rpx;
    color: #8F959E;
    line-height: 40rpx;
    border-bottom: 1px solid #EEEEEE;
    margin-top: 20rpx;

    &-left,
    &-right {
      display: flex;
      align-items: center;
    }
  }
}

.add-img {
  position: fixed;
  bottom: 20rpx;
  right: 20rpx;
}

.nodata {
  padding-top: 300rpx;
}
</style>
